package com.sbootv.view.login;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sbootv.utils.MD5Utils;
import com.sbootv.utils.R;
import com.sbootv.utils.ShiroUtils;

/**
 * 登陆验证
 * @author romanceling
 *
 */
@Controller
public class Login {

	/**
	 * 跳转到登陆界面
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String gotoLogin(){
		return "login";
	}
	
	/**
	 * 登陆验证方法
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/ajaxLogin",method=RequestMethod.POST)
	public R ajaxLogin(String username,String password){
		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return R.ok();
		} catch (AuthenticationException e) {
			return R.error(e.getMessage());
		}
	}
	
	/**
	 * 跳转到主界面
	 * @return
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(){
		return "index";
	}
	
	/**
	 * 退出登录
	 * @return
	 */
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:/login";
	}
}
